#include <QtGui>
#include <QtNetwork>
#include <iostream>

#include "tdownlad.h"

TDownlad::TDownlad(QObject *parent, QString file,QString _hash) :
    QThread(parent), finish(false)
{
    path = file.section('/', 0, -2);
    url = QString("http://l2updater.seobrya.com/").append(file);
    hash=_hash;
}

TDownlad::TDownlad(QObject *parent, QString file) :
    QThread(parent), finish(false)
{
    path = file.section('/', 0, -2);
    url = QString("http://l2updater.seobrya.com/").append(file);
}
//url.section('/', -1);

void TDownlad::startRequest(QUrl url)
{
    qDebug() << "url host: " << url.host();
    this->http = new QHttp(url.host(), QHttp::ConnectionModeHttp, 80);
    qDebug("http init");
    connect(http, SIGNAL(requestFinished(int, bool)),
                 this, SLOT(httpFinished(int, bool)));
    connect(http, SIGNAL(dataReadProgress(int, int)),
                 this, SLOT(downloadProgress(int, int)));
    QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
    qDebug() << path;
    if (path.isEmpty())
        path = "/";
    qDebug() << "state: " << http->state();
    reply = this->http->get(path, file);
    http->ignoreSslErrors();
    http->close();
    qDebug() << "get id" << reply;
    qDebug("http request send");
}

void TDownlad::downloadProgress(int un,int deux)
{
    emit updateProgress(un, deux);
}

void TDownlad::httpFinished(int id, bool error)
{
    qDebug("httpfinished");
    if (reply != id)
    {
        qDebug() << reply << " != " << id << "error: " << error << " " << http->errorString() << " " << http->state();
        emit sdlerror();
        return;
    }
    qDebug("http id match");
    qDebug("flushing file");
    //progressDialog->hide();
    file->flush();
    qDebug() <<"file size: "<< file->size();
    file->close();

    if (error) {
        file->remove();
        QMessageBox::information(0, tr("HTTP"),
                                          tr("Download failed: %1.")
                                          .arg(http->errorString()));
        emit updateSl(QString("Download failed"));
    } else {
        qDebug("file created");
        reply = 0;
        delete file;
        file = 0;
        emit done();
   }

}

void TDownlad::httpReadyRead()
{
    //if (file)
      //  file->write(reply->readAll());
}

QString TDownlad::CalcSha1(QString Path)
{
        QFile FileToHash(Path);
        QByteArray ba;
        QString HashOutput;
        QCryptographicHash CPU(QCryptographicHash::Sha1);
        if (FileToHash.open(QIODevice::ReadOnly))
        {
                while (!FileToHash.atEnd())
                {
                        ba = FileToHash.read(1024);
                        CPU.addData(ba);
                }
                FileToHash.close();
                ba = CPU.result();
                HashOutput = ba.toHex();
                return HashOutput;
        }
        else
        {
                HashOutput = "ERR";
                return HashOutput;
        }
}
#include <QTimer>
void TDownlad::run()
{
    //url = QString("http://www.my42.eu/~guss/updates/updater/update.lst");
    qDebug()<<"file: " <<path + "/" + url.path().section('/', -1);
    if(hash == this->CalcSha1(path + "/" + url.path().section('/', -1)) )
    {
        emit done();
        return;
    }
    else
    {
        QTimer tmp2;
        tmp2.start(500);
        QEventLoop loop2;
        connect(&tmp2, SIGNAL(timeout()), &loop2, SLOT(quit()));
        loop2.exec();
        QFileInfo fileInfo(url.path());
        QString fileName = fileInfo.fileName();
        if (fileName.isEmpty())
            fileName = "noname";

        if (QFile::exists(fileName)) {
            QFile::remove(fileName);
        }
        qDebug() << "dir: " << path << "file: " << fileName;
        if (path != "" && !QDir(QString(".")).exists(path))
        {
            QDir(QString(".")).mkpath(path);
        }
        QString tmp(fileName);
        if (path != "")
            tmp.insert(0, path + "/");
        file = new QFile(tmp);
        if (!file->open(QIODevice::WriteOnly)) {
            delete file;
            file = 0;
            qDebug("erreur open fichier");
            return;
        }
        // schedule the request
        httpRequestAborted = false;
        startRequest(url);
        QEventLoop loop;
        connect(http, SIGNAL(done(bool)), &loop, SLOT(quit()));
        loop.exec();
        qDebug("end loop thread");
    }
    return;
}
